package leetcode.InterviewClassic;

import java.util.HashMap;
import java.util.Map;

/**
 * Created With IntelliJ IDEA.
 * Descriptions:
 * User:Mr.Du
 * Date:2020/8/15
 * Time:14:21
 */
public class WordsFrequency {

    Map<String,Integer> mp = new HashMap<>();
    public WordsFrequency(String[] book) {
        for(String s : book){
            /**
             * 下面的方法可用map集合的getOrDefault方法来代替
             * public V getOrDefault(Object key, V defaultValue) {
             *         Node<K,V> e;
             *         return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
             *     }
             */
            if(mp.containsKey(s)){
                int tmp = mp.get(s);
                mp.put(s,++tmp);
            }else{
                mp.put(s,1);
            }
        }
    }

    public int get(String word) {
//        if(mp.containsKey(word))
//            return mp.get(word);
//        return 0;
        try{
            return mp.get(word);
        }catch(Exception e){
            return 0;
        }
    }

    public static void main(String[] args) {
        String[] book = {"i", "have", "an", "apple", "he", "have", "a", "pen"};
        WordsFrequency wordsFrequency = new WordsFrequency(book);
        wordsFrequency.get("you"); //返回0，"you"没有出现过
        wordsFrequency.get("have"); //返回2，"have"出现2次
        wordsFrequency.get("an"); //返回1
        wordsFrequency.get("apple"); //返回1
        wordsFrequency.get("pen"); //返回1


    }
}
